//
//  JCLNewfeatureView.swift
//  WeiBo
//
//  Created by DDC on 2017/9/14.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit

class JCLNewfeatureView: UIView {
    
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var enterBtn: UIButton!
    
    @IBOutlet weak var pageControl: UIPageControl!

    class func newfeatureView() -> JCLNewfeatureView{
    
        //从xib加载
        let nib = UINib(nibName: "JCLNewfeatureView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! JCLNewfeatureView
        //设置frame
        v.frame = UIScreen.main.bounds
        
        return v
    
    }
    @IBAction func enterBtnClick(_ sender: Any) {
        
        print("enter")
        self.removeFromSuperview()
        
    }
    //加载界面
    override func awakeFromNib() {
        
        // 添加图片到scrollView
        let count = 4
        // 图片大小属性
        let rect = UIScreen.main.bounds
        for i in 0..<count {
            // 依次添加图片
            let iv = UIImageView(image: UIImage(named: "new_feature_\(i + 1)"))
            // 设置图片的偏移量
            iv.frame = rect.offsetBy(dx: rect.width * CGFloat(i), dy: 0)
            // 添加到scrollview
            scrollView.addSubview(iv)
        }
        // 设置scrollview的属性
        scrollView.contentSize = CGSize(width: rect.width * CGFloat(count + 1), height: rect.height)
        scrollView.bounces = false
        scrollView.isPagingEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.delegate = self //设置代理
        
        enterBtn.isHidden = true
    }
    
}

extension JCLNewfeatureView : UIScrollViewDelegate{
    
    //减速滚动
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        if page == scrollView.subviews.count {
            
            removeFromSuperview()
        }
        
        enterBtn.isHidden = page != scrollView.subviews.count - 1
    }
    
    
    //滚动
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        enterBtn.isHidden = true
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        
        pageControl.currentPage = page
        
        pageControl.isHidden = (page == scrollView.subviews.count)
        
    }
}
